import React from 'react';
import { connect } from 'react-redux';
import { Icon, Tabs, WhiteSpace, ActionSheet, Button, Toast } from 'antd-mobile';
import FollowRecord from '../../components/Customer/FollowRecord';
import CustomerBase from '../../components/Customer/CustomerBase';
import CustomerInformation from '../../components/Customer/CustomerInformation';
import Certification from '../../components/Customer/Certification';
import ContactInfo from '../../components/Customer/ContactInfo';
import ContractList from '../../components/Customer/ContractList';
import CustomerInvoice from '../../components/Customer/CustomerInvoice';
import Modal from '../../components/common/Modal';
import NavBar from '../../components/common/NavBar';
import Footer from '../../components/common/Footer';

import ContactEdit from '../../components/Customer/ContactEdit';
import CustomerBaseEdit from '../../components/Customer/CustomerBaseEdit';
import CustomerInformationEdit from '../../components/Customer/CustomerInformationEdit';

import {withClient} from '../../hoc';

import './CustomerDetails.sass';

const icons = [
  'crmicon-weiqianyue',
  'crmicon-hezuozhong',
  'crmicon-yidaoqi',
  'crmicon-hezuodaoqi',
]
@withClient
@connect((state) => ({access_token: state.token.access_token}))
export default class CustomerDetails extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      contactEditVisible: false,
      customerBaseEditVisible: false,
      tabs: [
        { visible: true, title: '跟进记录', value: 1 },
        { visible: true, title: '客户基本信息', value: 2 },
        { visible: true, title: '客户资料', value: 3 },
        { visible: true, title: '认证信息', value: 4 },
        { visible: true, title: '联系人信息', value: 5 },
        { visible: true, title: '合同信息', value: 6 },
        { visible: true, title: '发票信息', value: 7 }
      ],
      phones: [{ tel: 13565263565, name: '张三' }, { name: '取消' }],
      selectedTab: 1,

      isQxb: false,
      baseCustomerData: {},
      customerInformation: {},
      globalEdit: true,
    };
    // console.log(props);
  }
  renderContent(content) {
    const { title, value } = content;

    return (
      <div>
        <WhiteSpace size="sm" />
        {value === 1 && <FollowRecord />}
        {value === 2 && <CustomerBase data={this.state.baseCustomerData} />}
        {value === 3 && <CustomerInformation isQxb={this.state.isQxb} data={{...this.state.customerInformation, businessType: this.state.baseCustomerData.businessType, businessTypeString: this.state.baseCustomerData.businessTypeString}} />}
        {value === 4 && <Certification />}
        {value === 5 && <ContactInfo />}
        {value === 6 && <ContractList />}
        {value === 7 && <CustomerInvoice />}
      </div>
    );
  }
  renderFooterText(value) {
    return value === 1
      ? '添加跟进记录'
      : value === 2
        ? '编辑'
        : value === 3
          ? '编辑'
          : value === 5
            ? '添加联系人'
            : value === 7
              ? '发票开具进度'
              : false;
  }
  footerOnClick = () => {
    const value = this.state.selectedTab;
    value === 1 && this.setState({ visible: true });
    value === 2 && this.setState({ customerBaseEditVisible: true });
    value === 3 && this.setState({ visible: true });
    value === 5 && this.setState({ contactEditVisible: true });
    value === 7 && this.setState({ visible: true });
  };
  renderTabsTitle(tabs) {
    return tabs.filter(item => item.visible === true);
  }

  getCustomerDetails = async () => { ///api/mobile/customer/getCustomerInformation
    const [res, customerInformation] = await Promise.all([
      this.props.client.post('/crm/api/mobile/customer/getCustomerDetail',{access_token: this.props.access_token, customerId: this.props.location.state.id}),
      this.props.client.post('/crm/api/mobile/customer/getCustomerInformation',{access_token: this.props.access_token, customerId: this.props.location.state.id}),
    ])
    if(Number(res.status) !== 0){
      Toast.fail(res.data.msg, 1)
    }else{
      // if(res.)
      let { tabs } = this.state;
      let selectedTab = 1;
      if(Number(res.data.customerStatus) === 0){
        tabs.map(item => {
          if (item.value === 4) item.visible = false;
          if (item.value === 7) item.visible = false;
        });
      }else if(Number(res.data.customerStatus) === 1){
        tabs.map(item => {
          if (item.value === 1) item.visible = false;
        });
        selectedTab = 2;
      }
      // this.setState({ tabs, selectedTab: 2 });
      this.setState({
        baseCustomerData: res.data,
        customerInformation: customerInformation.data,
        selectedTab,
        tabs,
        isQxb: Number(res.data.dockingQxb) === 1,
        globalEdit: Number(res.data.isAllowedOperate) === 1,    
      })
    }
  }

  onEditChange = async (label) => {
    const res = await this.props.client.post('/crm/api/mobile/customer/getCustomerDetail',{access_token: this.props.access_token, customerId: this.props.location.state.id || 1655556});
    if(Number(res.status) !== 0){
      Toast.fail(res.data.msg, 1)
    }else{
      this.setState({
        baseCustomerData: res.data,
        [label] : false,
      })
    }
  }

  componentWillMount() {
    this.getCustomerDetails();
    // const { tabs } = this.state;
    // tabs.map(item => {
    //   if (item.value === 1) item.visible = false;
    // });
    // this.setState({ tabs, selectedTab: 2 });
  }

  telOnclick = () => {
    const BUTTONS = this.state.phones.map(item => (
      <span>
        <span>{item.name}</span>
        {item.tel && <a href={`tel:${item.tel}`}>{item.tel}</a>}
      </span>
    ));
    ActionSheet.showActionSheetWithOptions(
      {
        options: BUTTONS,
        cancelButtonIndex: BUTTONS.length - 1,
        //   destructiveButtonIndex: BUTTONS.length - 2,
        // title: 'title',
        //   message: 'I am description, description, description',
        maskClosable: true,
        'data-seed': 'logId'
      },
      buttonIndex => {
        console.log(buttonIndex);
        this.setState({ clicked: BUTTONS[buttonIndex] });
      }
    );
  };

  render() {
    const {baseCustomerData, customerInformation} = this.state;
    const tabs = this.renderTabsTitle(this.state.tabs);
    const footerText = this.renderFooterText(this.state.selectedTab);
    const customerStatus = Number(baseCustomerData.customerStatus)
    return (
      <div className="customer-details-container">

        <ContactEdit 
          visible={this.state.contactEditVisible} 
          onSave={async() =>{
            await this.onEditChange('contactEditVisible');
          }}
          onCannel={() => this.setState({ contactEditVisible: false })} 
        />
        
        <CustomerBaseEdit 
          isQxb={this.isQxb}  
          data={baseCustomerData} 
          visible={this.state.customerBaseEditVisible} 
          onSave={async() =>{
            await this.onEditChange('customerBaseEditVisible');
          }}
          onCannel={() => this.setState({ customerBaseEditVisible: false })} 
        />

        <CustomerInformationEdit 
          isQxb={this.isQxb}  
          data={customerInformation.baseData}
          visible={this.state.customerInformationEditVisible} 
          onSave={async() =>{
            await this.onEditChange('customerInformationEditVisible');
          }}
          onCannel={() => this.setState({ customerInformationEditVisible: false })} 
        />

        <NavBar
          title="客户"
          leftContent={
            <span>
              <Icon type="left" />返回
            </span>
          }
          leftClick={() => {
            this.props.history.goBack();
          }}
        />

        <div className="customer-details-content">
          <div className="customer-details-name">
            <div className="customer-details-name-content">
              <div>{baseCustomerData.cName || '杭州金元标矩'}</div>
              <div>
                <i
                  onClick={this.telOnclick}
                  style={{ color: '#22aab0', fontSize: '0.36rem' }}
                  className="crmiconfont crmicon-dianhua"
                />
              </div>
            </div>
            <div className="customer-details-name-type">
              <i style={{color: customerStatus === 1 ? '#22bba0' : customerStatus === 0 ? '#FF6600' : '#888'}} className={`crmiconfont ${icons[customerStatus]}`} />
            </div>
          </div>
          <div className="customer-details-tabs-container">
            <Tabs
              tabs={tabs}
              onChange={(tab, index) => {
                this.setState({ selectedTab: tab.value });
              }}
              renderTabBar={props => <Tabs.DefaultTabBar {...props} page={4} />}
            >
              {(content) => {return this.renderContent(content)}}
            </Tabs>
          </div>
        </div>
        {footerText && <Footer disabled={!this.state.globalEdit} onClick={this.footerOnClick}>{footerText}</Footer>}
      </div>
    );
  }
}
